package config

import (
	"deploy-tools/utils"
	"fmt"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// Cache 允许动态改变全局变量，缓存到文件
type Cache struct {
	Values map[string]string `yaml:"values"`
	Key    string            `yaml:"key"`
	Path   string            `yaml:"path"`
}

func NewCache(key string) (*Cache, error) {
	var absPath string
	var err error
	absPath, err = filepath.Abs(fmt.Sprintf("./temp/cache_%s.yaml", key))
	if err != nil {
		return nil, err
	}
	_ = os.MkdirAll(filepath.Dir(absPath), os.ModePerm)

	yamlFile, err := os.ReadFile(absPath)
	if err != nil && !os.IsNotExist(err) {
		return nil, err
	}
	values := map[string]string{}
	if err == nil {
		err = yaml.Unmarshal(yamlFile, &values)
		if err != nil {
			return nil, err
		}
	}
	for k, v := range values {
		if strings.HasPrefix(v, "ENC(") {
			text := v[4 : len(v)-1]
			val, err := utils.Decrypt(text, GlobalConfig.EncryptKey)
			if err != nil {
				return nil, err
			}
			values[k] = val
		}
	}
	return &Cache{
		Values: values,
		Key:    key,
		Path:   absPath,
	}, nil
}

func (r *Cache) ClearAll() {
	r.Values = make(map[string]string)
	r.Write()
}

func (r *Cache) Cache(key string, value string) string {
	if key == "" {
		return ""
	}
	val := strings.TrimLeft(value, "\n")
	val = strings.TrimRight(val, "\n")
	r.Values[key] = val
	r.Write()
	return val
}

func (r *Cache) UnCache(key string) {
	if key == "" {
		return
	}
	delete(r.Values, key)
	r.Write()
}

func (r *Cache) GetCache(key string) string {
	if key == "" {
		return ""
	}
	return r.Values[key]
}

func (r *Cache) Write() {
	values := map[string]string{}
	for k, v := range r.Values {
		if GlobalConfig.EncryptKey == "" {
			values[k] = v
		} else {
			val, _ := utils.Encrypt(v, GlobalConfig.EncryptKey)
			values[k] = fmt.Sprintf("ENC(%s)", val)
		}
	}
	data, err := yaml.Marshal(&values)
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
		return
	}
	err = os.WriteFile(r.Path, data, os.ModePerm)
	if err != nil {
		log.Printf("yamlFile.WriteFile err   #%v ", err)
	}
}
